<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form" v-if="headerShow"></div>
      <div class="my-tool-bar"></div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" :default-active-key="tbsData.tableIndex" @change="changetabs">
        <a-tab-pane key="1" title="申购单待处理">
          <div class="xqdxx">
            <a-form
                size="mini"
                :model="pageData"
                layout="inline"
                v-if="permissionStore.hasPermisson('cgcgd.sgddclcx1')"
            >
              <a-form-item label="申购单号">
                <a-input
                    class="bacClass"
                    placeholder=""
                    v-model="pageData.dropDownData123"
                    @press-enter="huiche"
                    allow-clear
                />
              </a-form-item>
              <a-form-item label="主体">
                <a-select popup-container="html"
                          class="bacClass"
                          :loading="loading"
                          @search="handleSearchZt"
                          v-model="pageData.companyEntity"
                          style="width: 150px"
                          :filter-option="false"
                          allow-search
                          allow-clear
                          @focus="focusSelZt"
                >
                  <a-option
                      v-for="item in pageData.companyEntityList"
                      :value="item['company_entity']"
                  >{{ item['company_entity'] }}
                  </a-option
                  >
                </a-select>
              </a-form-item>
            </a-form>
            <Toolbar
                :items="[
                `${permissionStore.hasPermisson('cgcgd.sgddclcx1') ? '查询' : ''}`,
                `${permissionStore.hasPermisson('cgcgd.sgddclcjcgd1') ? '创建采购单' : ''}`,
              ]"
                @select="selectSh"
                @CreateCai="handleBeforeOk"
            ></Toolbar>
          </div>
          <a-spin
              :loading="pageData.pageLoading"
              tip="加载中"
              dot
              style="height: 100%; width: 100%; z-index: 999"
          >
            <AgGridVuesCopys
                :rowHeight="33"
                :headerHeight="33"
                :suppressCopyRowsToClipboard="true"
                rowSelection="multiple"
                @grid-ready="gridReadys11"
                style="height: 85%"
                :defaultColDef="defaultColDefs11"
                class="ag-theme-alpine"
                :rowData="table.dataList"
                :columnDefs="tcs11"
                :localeText="localeText1"
            ></AgGridVuesCopys>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane key="3" title="申购单已处理">
          <div class="xqdxx">
            <a-form
                size="mini"
                :model="pageData"
                layout="inline"
                v-if="permissionStore.hasPermisson('cgcgd.sgdyclcx1')"
            >
              <a-form-item label="申购单号">
                <a-input
                    class="bacClass"
                    placeholder=""
                    v-model="pageData.dropDownData"
                    @press-enter="huiche3"
                    allow-clear
                />
              </a-form-item>
            </a-form>
            <div style="text-align: right; width: 100%">
              <Toolbar
                  :items="[`${permissionStore.hasPermisson('cgcgd.sgdyclcx1') ? '查询' : ''}`]"
                  @select="cxAllYtj"
              >
              </Toolbar>
            </div>
          </div>
          <a-spin
              :loading="pageData.pageLoading"
              tip="加载中"
              dot
              style="height: 100%; width: 100%; z-index: 999"
          >
            <AgGridVuesCopys
                :rowHeight="33"
                :headerHeight="33"
                :suppressCopyRowsToClipboard="true"
                rowSelection="multiple"
                @grid-ready="gridReadysz"
                style="height: 85%"
                :defaultColDef="defaultColDefsz"
                class="ag-theme-alpine"
                :rowData="pageData.xqDataList"
                :columnDefs="tcsz"
                :localeText="localeText1"
            ></AgGridVuesCopys>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane key="2" title="采购单查询/修改">
          <pageTabelLayout>
            <template #pageHeader>
              <div class="xqdxx">
                <a-form
                    size="mini"
                    :model="pageData"
                    layout="inline"
                    v-if="permissionStore.hasPermisson('cgcgd.cgdcx1')"
                >
                  <a-form-item label="采购单号">
                    <a-input
                        class="bacClass"
                        placeholder=""
                        v-model="pageData.dropDownData1"
                        @press-enter="huiche2"
                        allow-clear
                    />
                  </a-form-item>
                </a-form>
                <Toolbar
                    :items="[`${permissionStore.hasPermisson('cgcgd.cgdcx1') ? '查询' : ''}`]"
                    @select="selectInfo"
                >
                </Toolbar>
              </div>
            </template>
            <template #pageTabel>
              <a-spin
                  :loading="pageData.pageLoading"
                  tip="加载中"
                  dot
                  style="height: 100%; width: 100%; z-index: 999"
              >
                <AgGridVuesCopys
                    :rowHeight="33"
                    :headerHeight="33"
                    :suppressCopyRowsToClipboard="true"
                    rowSelection="multiple"
                    @grid-ready="gridReadys"
                    style="height: calc(100% - 45px)"
                    :defaultColDef="defaultColDefs"
                    class="ag-theme-alpine"
                    :rowData="isDataLists"
                    :columnDefs="tcs"
                    :localeText="localeText1"
                ></AgGridVuesCopys>
                <paginationCopys
                    :page-size-options="pagingList1"
                    v-if="pageData.isKey == 2"
                    :total="pagination.total"
                    show-total
                    show-jumper
                    show-page-size
                    @change="PageSize"
                    @page-size-change="change1"
                    style="justify-content: center"
                    :page-size="pagination.pageSize"
                    :current="pagination.page"
                />
              </a-spin>
            </template>
          </pageTabelLayout>
        </a-tab-pane>
        <a-tab-pane key="4" title="采购单已处理">
          <pageTabelLayout>
            <template #pageHeader>
              <div class="xqdxx">
                <a-form
                    size="mini"
                    :model="pageData"
                    layout="inline"
                    v-if="permissionStore.hasPermisson('cgcgd.cgdyclcx1')"
                >
                  <a-form-item label="申购单号">
                    <a-input
                        class="bacClass"
                        placeholder=""
                        v-model="pageData.dropDownData4"
                        allow-clear
                        @press-enter="huiche4"
                    />
                  </a-form-item>
                </a-form>
                <div style="text-align: right; width: 100%">
                  <Toolbar
                      :items="[
                  `${permissionStore.hasPermisson('cgcgd.cgdyclcx1') ? '查询' : ''}`,
                  `${permissionStore.hasPermisson('cgcgd.cgdycldy1') ? '打印' : ''}`,
                ]"
                      @select="selectSh4"
                      @dyBoufei="printPdf"
                  ></Toolbar>
                </div>
              </div>
            </template>
            <template #pageTabel>
              <a-spin
                  :loading="pageData.pageLoading"
                  tip="加载中"
                  dot
                  style="height: 100%; width: 100%; z-index: 999"
              >
                <AgGridVuesCopys
                    :rowHeight="33"
                    :headerHeight="33"
                    :suppressCopyRowsToClipboard="true"
                    rowSelection="multiple"
                    @grid-ready="gridReady4"
                    style="height: calc(100% - 45px)"
                    :defaultColDef="defaultColDef4"
                    class="ag-theme-alpine"
                    :rowData="table.dataList"
                    :columnDefs="tc4"
                    :localeText="localeText1"
                ></AgGridVuesCopys>
                <paginationCopys
                    :page-size-options="pagingList1"
                    v-if="pageData.isKey == 4"
                    :total="pagination.total"
                    show-total
                    show-jumper
                    show-page-size
                    @change="PageSize"
                    @page-size-change="change1"
                    style="justify-content: center"
                    :page-size="pagination.pageSize"
                    :current="pagination.page"
                />
              </a-spin>
            </template>
          </pageTabelLayout>
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-drawer
        style="z-index: 999"
        ok-text="保存"
        cancel-text="关闭"
        :drawer-style="{ zIndex: 1001, border: '1px solid #ccc' }"
        popup-container=".arco-tabs-content"
        height="100%"
        placement="bottom"
        :visible="pageData1.showAdd"
        unmountOnClose
        @ok="sideOks"
        @cancel="cancelis"
        @close="onClose"
        :mask-closable="false"
    >
      <template #title>
        {{ pageData1.title }}
      </template>
      <div style="height: 100%">
        <div
            style="width: 1540px; overflow: auto; padding-right: 5px; height: 100%"
            class="scrollbar"
        >
          <el-scrollbar style="height: 100%">
            <a-form
                ref="formRef"
                layout="inline"
                size="mini"
                :model="dataForm"
                :label-col-props="{ span: 11 }"
                :wrapper-col-props="{ span: 13 }"
            >
              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="主体"
                  field="companyEntity"
              >
                <a-input
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.companyEntity"
                    disabled
                    class="bacClass"
                />
              </a-form-item>
              <!-- <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="结算公司" field="settlementCompanyName"
                :rules="[{ required: true, message: '结算公司必填' }]" :validate-trigger="['change', 'blur']">
                <a-cascader v-model="dataForm.settlementCompanyName" :options="pageData.firmGroupList1" allow-clear
                  ref="casOb2" @change="cascaderChange2($event, dataForm.settlementCompanyName)" class="bacClass"
                  :title="pageData.title2"   :loading="pageData.loading2" />
              </a-form-item> -->
              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="编制日期"
                  field="purchaseDate"
                  disabled
              >
                <a-date-picker popup-container="html"
                               style="width: 13.5rem"
                               :time-picker-props="{ defaultValue: '00:00:00' }"
                               format="YYYY-MM-DD"
                               v-model="dataForm.purchaseDate"
                               class="bacClass"
                />
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="供应商名称"
                  field="providerId"
                  :rules="[{ required: true, message: '供应商名称必填' }]"
                  :validate-trigger="['change', 'blur']"
              >
                <a-select popup-container="html"
                          class="bacClass"
                          :style="{ width: '13.5rem' }"
                          :loading="loading"
                          @search="handleSearchz"
                          @change="proChange"
                          v-model="dataForm.providerId"
                          :filter-option="false"
                          allow-search
                          allow-clear
                          @focus="focusSelz"
                >
                  <a-option v-for="item in pageData.nameListz" :value="item.id">{{
                      item.providerName
                    }}
                  </a-option>
                </a-select>
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="采购类型"
                  field="purchaseType"
                  :rules="[{ required: true, message: '采购类型必填' }]"
                  :validate-trigger="['change', 'blur']"
              >
                <a-select popup-container="html"
                          class="bacClass"
                          :style="{ width: '13.5rem' }"
                          :loading="loading"
                          @search="handleSearchs"
                          v-model="dataForm.purchaseType"
                          :filter-option="false"
                          allow-search
                          allow-clear
                          @focus="focusSels"
                >
                  <a-option v-for="item in pageData.nameLists as any" :value="item.purchaseType">{{
                      item.purchaseType
                    }}
                  </a-option>
                </a-select>
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="采购员"
                  field="createName"
              >
                <a-input
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.createName"
                    disabled
                    class="bacClass"
                />
              </a-form-item>

              <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="结算方式">
                <a-select popup-container="html"
                          class="bacClass"
                          :style="{ width: '13.5rem' }"
                          :loading="loadingx"
                          p
                          @search="handleSearchx"
                          v-model="dataForm.settlementType"
                          :filter-option="false"
                          allow-search
                          allow-clear
                          @focus="focusSelx"
                >
                  <a-option v-for="item in pageData.nameList as any" :value="item.settlementName">{{
                      item.settlementName
                    }}
                  </a-option>
                </a-select>
              </a-form-item>

              <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="交货方式">
                <a-select popup-container="html"
                          class="bacClass"
                          :style="{ width: '13.5rem' }"
                          :loadingqq="loading"
                          @search="handleSearchqq"
                          v-model="dataForm.logisticType"
                          :filter-option="false"
                          allow-search
                          allow-clear
                          @focus="focusSelqq"
                >
                  <a-option v-for="item in pageData.nameListqq" :value="item.deliveryType">{{
                      item.deliveryType
                    }}
                  </a-option>
                </a-select>
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="计划交货日期"
                  field="planDeliveryDate"
                  :rules="[{ required: true, message: '日期必填' }]"
                  :validate-trigger="['change', 'blur']"
              >
                <a-date-picker popup-container="html"
                               class="bacClass"
                               style="width: 13.5rem"
                               :time-picker-props="{ defaultValue: '00:00:00' }"
                               format="YYYY-MM-DD"
                               v-model="dataForm.planDeliveryDate"
                />
              </a-form-item>
              <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="采购单号">
                <a-input
                    disabled
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.purchaseCode"
                    class="bacClass"
                />
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="签订地点"
                  field="signAddress"
                  :validate-trigger="['change', 'blur']"
              >
                <a-input
                    class="bacClass"
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.signAddress"
                />
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="制单人"
                  field="createName"
              >
                <a-input
                    disabled
                    class="bacClass"
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.createName"
                />
              </a-form-item>

              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="交货说明"
                  field="deliveryExplain"
                  :validate-trigger="['change', 'blur']"
              >
                <a-input
                    class="bacClass"
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.deliveryExplain"
                />
              </a-form-item>

              <!-- <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="采购公司" field="useCompany"
                :rules="[{ required: true, message: '采购公司必填' }]" :validate-trigger="['change', 'blur']">
                <a-cascader v-model="dataForm.useCompany" :options="pageData.firmGroupList" allow-clear ref="casOb"
                  @change="cascaderChange($event, dataForm.useCompany)" :title="pageData.title"
                  :loading="pageData.loading" disabled class="bacClass" />
              </a-form-item> -->

              <!-- <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="采购部门" field="useDepartment"
                :rules="[{ required: true, message: '采购部门必填' }]" :validate-trigger="['change', 'blur']">
                <a-cascader v-model="dataForm.useDepartment" :options="pageData.bmList" allow-clear ref="casOb1"
                  @change="cascaderChange1" :title="pageData.title1"   :loading="pageData.loading1"
                  disabled />
              </a-form-item> -->
              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="合同号"
                  field="orderNo"
                  :validate-trigger="['change', 'blur']"
              >
                <a-input
                    class="bacClass"
                    :style="{ width: '13.5rem' }"
                    v-model="dataForm.orderNo"
                />
              </a-form-item>
              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="币种"
                  field="moneyType"
                  :rules="[{ required: true, message: '币种必填' }]"
                  :validate-trigger="['change', 'blur']"
              >
                <a-select popup-container="html"
                          class="bacClass"
                          :style="{ width: '13.5rem' }"
                          v-model="dataForm.moneyType"
                          allow-clear
                          @focus="focusBl"
                >
                  <a-option v-for="item in pageData.blTypeList" :value="item['detailName']">{{
                      item['detailName']
                    }}
                  </a-option>
                </a-select>
              </a-form-item>
              <a-form-item
                  :style="{ width: '355px' }"
                  label-col-flex="120px"
                  label="送货地址"
                  field="address"
                  :validate-trigger="['change', 'blur']"
                  :rules="[{ required: true, message: '送货地址必填' }]"
              >
                <a-select popup-container="html"
                          class="bacClass"
                          v-model="dataForm.address"
                          @search="searchAddress"
                          @focus="focusAddress"
                          allow-clear
                          allow-search
                          :filter-option="false"
                >
                  <a-option v-for="item in pageData.dzList" :value="item['detailName']"
                  >{{ item['detailName'] }}
                  </a-option>
                </a-select>
              </a-form-item>
              <a-form-item
                  :style="{ width: '1490px' }"
                  label-col-flex="120px"
                  label="备注"
                  field="remark"
              >
                <a-textarea
                    class="bacClass"
                    v-model="dataForm.remark"
                    allow-clear
                    show-word-limit
                />
              </a-form-item>
            </a-form>
            <a-spin
                :loading="pageData.pageLoading"
                tip="加载中"
                dot
                style="height: 100%; width: 99%; z-index: 999; overflow-y: auto"
            >
              <AgGridVuesCopys
                  :rowHeight="33"
                  :headerHeight="33"
                  :suppressCopyRowsToClipboard="true"
                  rowSelection="multiple"
                  @grid-ready="gridReadysz111"
                  style="height: 450px; width: 2000px"
                  :defaultColDef="defaultColDefsz111"
                  class="ag-theme-alpine"
                  :rowData="pageData.tqDataList"
                  :columnDefs="tcsz111"
              ></AgGridVuesCopys>
            </a-spin>
          </el-scrollbar>
        </div>
      </div>
    </a-drawer>
    <a-modal
        v-model:visible="visible1"
        title="采购单详情"
        :width="1400"
        :footer="false"
        :draggable="true"
    >
      <a-table
          :style="{
          height: '100%',
          marginTop: '10px',
        }"
          stripe
          :bordered="true"
          :scrollbar="true"
          sticky-header
          :columns="tableColumns3"
          :data="pageData.isDetailsList"
      >
      </a-table>
    </a-modal>
    <a-modal
        v-model:visible="visible2"
        title="申购单详情"
        :width="1300"
        :footer="false"
        :draggable="true"
    >
      <a-table
          :style="{
          height: '100%',
          marginTop: '10px',
        }"
          stripe
          :bordered="true"
          :scrollbar="true"
          sticky-header
          :columns="tableColumns4"
          :data="pageData.isDetailsList"
      >
      </a-table>
    </a-modal>
    <a-modal v-model:visible="visiblecg4" ok-text="打印" @ok="print" :width="800">
      <template #title> 采购订单</template>
      <div id="ofpurchase2" style="height: 1090px">
        <h2 style="text-align: center">采购订单</h2>
        <div id="dys">
          <div>供应商名称:{{ idDtaDys.providerName }}</div>
          <div>联系人:{{ idpro.contactPerson }}</div>
          <div>联系电话:{{ idpro.contactPhone }}</div>
        </div>
        <div id="dys">
          <div>供应商地址:{{ idpro.providerAddress }}</div>
          <div>付款方式:{{ idDtaDys.settlementType }}</div>
        </div>
        <div id="dys">
          <div>采购单号:{{ idDtaDys.purchaseCode }}</div>
          <div>采购员:{{ idDtaDys.createName }}</div>
          <div>下单日期:{{ dataTime[0] }}</div>
        </div>
        <div id="dys">
          <div>送货地址:{{ idDtaDys.settlementCompanyName }}</div>
          <div>货币:{{ idDtaDys.moneyType }}</div>
        </div>
        <table class="isTable">
          <tr>
            <th>物料名称</th>
            <th>规格</th>
            <th>单位</th>
            <th>采购数量</th>
            <th>交期</th>
          </tr>
          <tr v-for="item in idDtaDy">
            <!-- <td>{{ idDtaDys.providerName }}</td> -->
            <td>{{ item.materialName }}</td>
            <td>{{ item.specName }}</td>
            <td>{{ item.unit }}</td>
            <td>{{ item.purchaseNum }}</td>
            <td>{{ dataTime2[0] }}</td>
          </tr>
        </table>
      </div>
    </a-modal>
    <a-modal
        v-model:visible="visible5"
        @ok="handleOk5"
        @cancel="handleCancel5"
        :width="1200"
        :draggable="true"
        :footer="false"
    >
      <template #title> 历史单价</template>
      <a-table
          :style="{
          height: '560px',
          marginTop: '10px',
        }"
          stripe
          :bordered="true"
          :scrollbar="true"
          sticky-header
          :columns="tableColumns5"
          :data="pageData.historicalList"
      >
      </a-table>
      <paginationCopys
          :page-size-options="[10]"
          :total="pagination2.total"
          show-total
          show-jumper
          show-page-size
          @change="PageSize1"
          @page-size-change="change2"
          style="justify-content: center"
          :page-size="pagination2.pageSize"
          :current="pagination2.page"
      />
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post} from '@/api/http'
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import {ref, reactive, onMounted, toRefs, getCurrentInstance} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Form, Message, Modal} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import {String} from 'lodash'
import {baseURL} from '@/api/axios.config'
import axios from 'axios'
import XqService from '../orderpurchase/service/xq/index'
import {right} from '@popperjs/core'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import printJS from 'print-js'
import {Console} from 'console'
import usePermission from '@/store/modules/permission'
import {slicing} from '@/utils/caseFrimAndSecRig'
import PageTabelLayout from "@/components/pageTabelLayout.vue";

interface SettlementType {
  id: any
  uid: any
  purchaseCode: any
  purchaseDate: any
  providerId: any
  providerName: any
  purchaseType: any
  purchasePerson: any
  settlementType: any
  logisticType: any
  auditState: any
  auditPerson: any
  auditDate: any
  planDeliveryDate: any
  settlementCompany: any
  signAddress: any
  customName: any
  deliveryExplain: any
  useDepartment: any
  orderNo: any
  moneyType: any
  remark: any
  deleteState: any
  createName: any
  useCompany: any
  useCompanyName: any
  settlementCompanyName: any
  address: any
  useDepartmentId: any
  settlementCompanyId: any
  purchaseNum: any
  useCompanys: any
  materialCode: any
  companyEntity: any
}

export default {
  name: 'OrderOfPurchase',
  // props: ['vals'],
  setup() {
    const {proxy} = getCurrentInstance()
    const tabValue = ref<any>(proxy.$route.query.name)
    const tbsData = reactive({
      tableIndex: tabValue.value,
    })
    const XqServices = new XqService()
    const xqOptions = XqServices.xqArrays
    const zjArrays = XqServices.zjArray
    let zjArrays1: any = ref([
      {
        children: [{label: ''}],
      },
    ])
    const casaders = (val: any) => {
      dataForm.useDepartmentId = ''
      zjArrays1.value = zjArrays.value.filter((res: any) => {
        return val == res.value
      })
    }

    function change1(val: any) {
      if (pageData.isKey == 2) {
        pagination.pageSize = val
        cxAllInfo()
      } else if (pageData.isKey == 4) {
        pagination.pageSize = val
        selectSh4()
      }
    }

    function PageSize(val: any) {
      if (pageData.isKey == 2) {
        pagination.page = val
        cxAllInfo()
      } else if (pageData.isKey == 4) {
        pagination.pageSize = val
        selectSh4()
      }
    }

    function change2(val: any) {
      pagination2.pageSize = val
      console.log(val)

      ViewHistoricalUnitPrice(gridOptionsz111.value.getSelectedRows()[0])
    }

    function PageSize1(val: any) {
      pagination2.page = val
      console.log(val)
      ViewHistoricalUnitPrice(gridOptionsz111.value.getSelectedRows()[0])
    }

    const headerShow = ref<boolean>(true)

    function doRefresh() {
      pageData.pageLoading = true
      post({
        url: 'dwPurchase/purchaseNeed/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: 0,
          needDepartment: pageData.dropDownDataq,
          materialName: pageData.dropDownDataqs,
          warehouseName: pageData.dropDownDataqsz,
          ...pageData.dropDownDataqszs,
          specName: pageData.specifications,
          needPerson: pageData.PeopleNeed,
          purchaseNeedCode: pageData.DemandNumber,
          applyCode: pageData.dropDownData,
          purchaseCode: pageData.dropDownData1,
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              pagination.setTotalSize(data.total)
              // console.log(table.dataList)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection()
    const pagination = usePagination(doRefresh)
    const pagination1 = usePagination(doRefreshs)
    const pagination2 = usePagination(ViewHistoricalUnitPrice)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns2 = useTableColumn([
      {
        title: '采购单号',
        key: 'purchaseCode',
        dataIndex: 'purchaseCode',
        width: 150,
      },
      {
        title: '编制日期',
        key: 'purchaseDate',
        dataIndex: 'purchaseDate',
        width: 150,
      },
      {
        title: '供应商名称',
        key: 'providerName',
        dataIndex: 'providerName',
        width: 150,
      },
      {
        title: '采购类型',
        key: 'purchaseType',
        dataIndex: 'purchaseType',
        width: 150,
      },
      {
        title: '需求类型',
        key: 'needType',
        dataIndex: 'needType',
        width: 150,
      },
      {
        title: '采购员',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },

      {
        title: '结算方式',
        key: 'settlementType',
        dataIndex: 'settlementType',
        width: 150,
      },
      {
        title: '交货方式',
        key: 'logisticType',
        dataIndex: 'logisticType',
        width: 150,
      },
      {
        title: '审核人',
        key: 'auditPerson',
        dataIndex: 'auditPerson',
        width: 150,
      },
      {
        title: '计划交货日期',
        key: 'planDeliveryDate',
        dataIndex: 'planDeliveryDate',
        width: 150,
      },
      {
        title: '结算公司',
        key: 'settlementCompanyName',
        dataIndex: 'settlementCompanyName',
        width: 150,
      },
      {
        title: '签订地点',
        key: 'signAddress',
        dataIndex: 'signAddress',
        width: 150,
      },
      {
        title: '制单人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '交货说明',
        key: 'deliveryExplain',
        dataIndex: 'deliveryExplain',
        width: 150,
      },
      // {
      //   title: '采购公司',
      //   key: 'useCompanyName',
      //   dataIndex: 'useCompanyName',
      //   width: 150,
      // },
      // {
      //   title: '采购部门',
      //   key: 'useDepartment',
      //   dataIndex: 'useDepartment',
      //   width: 150,
      // },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '合同号',
        key: 'orderNo',
        dataIndex: 'orderNo',
        slotName: 'orderNo',
        width: 150,
      },
      {
        title: '币种',
        key: 'moneyType',
        dataIndex: 'moneyType',
        width: 150,
      },

      {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right',
      },
    ])
    const tableColumns1 = useTableColumn([
      {
        title: '采购单号',
        key: 'purchaseCode',
        dataIndex: 'purchaseCode',
        width: 150,
      },
      {
        title: '采购公司',
        key: 'useCompanyName',
        dataIndex: 'useCompanyName',
        width: 150,
      },
      {
        title: '采购部门',
        key: 'useDepartment',
        dataIndex: 'useDepartment',
        width: 150,
      },
      {
        title: '采购人',
        key: 'purchasePerson',
        dataIndex: 'purchasePerson',
        width: 150,
      },
      {
        title: '采购类型',
        key: 'purchaseType',
        dataIndex: 'purchaseType',
        width: 150,
      },
      {
        title: '计划交货日期',
        key: 'planDeliveryDate',
        dataIndex: 'planDeliveryDate',
        width: 150,
      },
      {
        title: '制单人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '送货地址',
        key: 'address',
        dataIndex: 'address',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        slotName: 'remark',
        width: 150,
      },
      {
        title: '操作',
        key: 'action',
        dataIndex: 'action',
        slotName: 'action',
        width: 150,
        fixed: 'right',
      },
    ])
    const tableColumns3 = useTableColumn([
      {
        title: '采购公司',
        key: 'useCompanys',
        dataIndex: 'useCompanys',
        width: 150,
      },
      {
        title: '物料大类',
        key: 'bigClassName',
        dataIndex: 'bigClassName',
        width: 150,
      },
      {
        title: '物料编号',
        key: 'materialCode',
        dataIndex: 'materialCode',
        width: 150,
      },
      {
        title: '物料名称',
        key: 'materialName',
        dataIndex: 'materialName',
        width: 150,
      },
      {
        title: '规格',
        key: 'specName',
        dataIndex: 'specName',
        width: 150,
      },
      {
        title: '申购数量',
        key: 'applyNum',
        dataIndex: 'applyNum',
        width: 150,
      },
      {
        title: '库存数量',
        key: 'stockNum',
        dataIndex: 'stockNum',
        slotName: 'stockNum',
        width: 150,
      },
      {
        title: '单位',
        key: 'unit',
        dataIndex: 'unit',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        slotName: 'remark',
        width: 150,
      },
      {
        title: '采购部门',
        key: 'useDepartment',
        dataIndex: 'useDepartment',
        width: 150,
      },
      {
        title: '采购数量',
        key: 'purchaseNum',
        dataIndex: 'purchaseNum',
        slotName: 'purchaseNum',
        width: 150,
      },
      {
        title: '采购单位',
        key: 'purchaseUnit',
        dataIndex: 'purchaseUnit',
        width: 150,
      },
      // {
      //   title: '欠数',
      //   key: 'oweNum',
      //   dataIndex: 'oweNum',
      //   slotName: 'oweNum',
      //   width: 150,
      // },
      // {
      //   title: '采购公司',
      //   key: 'useCompanys',
      //   dataIndex: 'useCompanys',
      //   width: 150,
      // },
      {
        title: '单价',
        key: 'price',
        dataIndex: 'price',
        slotName: 'price',
        width: 150,
      },
      {
        title: '税率',
        key: 'taxRate',
        dataIndex: 'taxRate',
        slotName: 'taxRate',
        width: 150,
      },
      {
        title: '总价',
        key: 'amount',
        dataIndex: 'amount',
        slotName: 'amount',
        width: 150,
      },
      {
        title: '转化比例',
        key: 'convertRate',
        dataIndex: 'convertRate',
        width: 150,
      },
      {
        title: '历史单价',
        key: 'HistoricalPrice',
        dataIndex: 'HistoricalPrice',
        slotName: 'HistoricalPrice',
        width: 150,
      },
    ])
    const tableColumns5 = useTableColumn([
      {
        title: '采购公司',
        key: 'firmName',
        dataIndex: 'firmName',
        width: 150,
      },
      {
        title: '物料编号',
        key: 'materialCode',
        dataIndex: 'materialCode',
        width: 150,
      },
      {
        title: '物料名称',
        key: 'materialName',
        dataIndex: 'materialName',
        width: 150,
      },
      {
        title: '采购单号',
        key: 'purchaseCode',
        dataIndex: 'purchaseCode',
        width: 150,
      },
      {
        title: '供应商',
        key: 'supplierName',
        dataIndex: 'supplierName',
        width: 150,
      },
      {
        title: '采购数量',
        key: 'purchaseNum',
        dataIndex: 'purchaseNum',
        width: 150,
      },
      {
        title: '采购单位',
        key: 'unit',
        dataIndex: 'unit',
        width: 150,
      },
      {
        title: '单价',
        key: 'price',
        dataIndex: 'price',
        width: 150,
      },
      {
        title: '总价',
        key: 'totalPrice',
        dataIndex: 'totalPrice',
        width: 150,
      },
    ])
    const pageData = reactive<{
      nameList: any
      nameLists: any
      nameListz: any
      nameListq: any
      nameListqs: any
      nameListqq: any
      specifications: any
      DemandNumber: any
      PeopleNeed: any
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      dropDownDataq: any
      dropDownDataqs: any
      dropDownDataqsz: any
      dropDownDataqszs: any
      pageLoading: boolean
      rHeight: any
      blTypeList: any[]
      xqDataList: any[]
      isKey: any
      isDetailsList: any[]
      isDetailsList1: any[]
      tqDataList: any[]
      dropDownData1: any
      firmList: any[]
      firmListsy: any[]
      bmListsy: any[]
      dropDownData123: any
      bmList: any[]
      title: any
      isShow: boolean
      firmGroupList: []
      loading: boolean
      title1: any
      loading1: boolean
      firmGroupList1: []
      title2: any
      loading2: boolean
      dropDownData4: any
      isDetail: boolean
      isEdit: boolean
      dzList: any[]
      historicalList: any[]
      companyEntity: any
      companyEntityList: any[]
    }>({
      dzList: [],
      isDetail: false,
      isEdit: false,
      bmList: [],
      title: '',
      isShow: true,
      firmGroupList: [],
      loading1: false,
      title1: '',
      loading: false,
      dropDownData4: '',
      firmGroupList1: [],
      loading2: false,
      title2: '',
      dropDownData123: '',
      nameList: [],
      nameLists: [],
      nameListz: [],
      nameListq: [],
      nameListqs: [],
      nameListqq: [],
      specifications: '',
      PeopleNeed: '',
      DemandNumber: '',
      showAdd: false,
      sideTitle: '',
      dropDownData: '',
      dropDownDataq: '',
      dropDownDataqs: '',
      dropDownDataqsz: '',
      dropDownDataqszs: {},
      pageLoading: false,
      rHeight: '',
      blTypeList: [],
      xqDataList: [],
      isKey: '1',
      isDetailsList: [],
      isDetailsList1: [],
      tqDataList: [],
      dropDownData1: '',
      firmList: [],
      firmListsy: [],
      bmListsy: [],
      historicalList: [],
      companyEntity: '',
      companyEntityList: [],
    })
    const pageData1 = reactive({
      showAdd: false,
      title: '创建采购单',
    })
    //下拉框得到焦点
    let cl: any = null
    const focusSel = (num: any) => {
      cl = num

      selCxAll({applyCode: '', processedState: cl, selectType: cl, auditState: 1})
    }
    //下拉数据
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {applyCode: value, processedState: cl, selectType: cl, auditState: 1}
        loading.value = true
        window.setTimeout(() => {
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        }, 200)
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'dwPurchase/PurchaseApply/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //采购单模糊查询
    //下拉数据
    //下拉框得到焦点
    const focusSel1 = () => {
      selCxAll1({purchaseCode: '', selectType: 1})
    }
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = {applyCode: value, selectType: 1}
        loading.value = true
        window.setTimeout(() => {
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        }, 200)
      } else {
        options.value = []
      }
    }
    const options1 = ref<any>(pageData.nameList)

    function selCxAll1(val: any) {
      post({
        url: 'dwPurchase/PurchaseOrder/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      pageData.isKey = tbsData.tableIndex
      // 第一个页面需要在刚进入就调用一次  切换tap时也需要调用
      if (pageData.isKey == 1) {
        selectSh()
      } else if (pageData.isKey == 2) {
        cxAllInfo()
      } else if (pageData.isKey == 3) {
        cxAllYtj()
      } else if (pageData.isKey == 4) {
        selectSh4()
      }
      // selCxAll({});
      // 切换tap到本页面执行的方法
      emitter.on('OrderOfPurchase', () => {
        // selCxAll({});
        if (pageData.isKey == 1) {
          selectSh()
        } else if (pageData.isKey == 2) {
          cxAllInfo()
        } else if (pageData.isKey == 3) {
          cxAllYtj()
        } else if (pageData.isKey == 4) {
          selectSh4()
        }
      })
      pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
      //表格的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight

        //表格的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight
        }
      })
    })
    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      //清空数据
      for (const key in dataForm) {
        if (key == 'id') {
          dataForm.id = null
        } else {
          dataForm[key] = ''
        }
      }
      isDataLists.value = []
      pageData.showAdd = true
      pageData.sideTitle = '新增需求单'
    }

    const dataForm = reactive<SettlementType>({
      id: null,
      uid: '',
      purchaseCode: '',
      purchaseDate: '',
      providerId: '',
      providerName: '',
      purchaseType: '',
      purchasePerson: '',
      settlementType: '',
      logisticType: '',
      auditState: '',
      auditPerson: '',
      auditDate: '',
      planDeliveryDate: '',
      settlementCompany: '',
      signAddress: '',
      customName: '',
      deliveryExplain: '',
      useDepartment: '',
      orderNo: '',
      moneyType: '',
      remark: '',
      deleteState: '',
      createName: '',
      useCompany: null,
      useCompanyName: '',
      settlementCompanyName: '',
      address: '',
      useDepartmentId: null,
      settlementCompanyId: null,
      purchaseNum: null,
      useCompanys: '',
      materialCode: '',
      companyEntity: '',
    })
    const formRef = ref<FormInstance>()

    const editHandler = (record: SettlementType) => {
      getFirmGroup()
      pageData1.showAdd = true
      selectedRowKeys.value.push(record['id'])
      pageData1.title = '修改采购单'
      for (var key in record) {
        dataForm[key] = record[key]
      }
      proChange()
      //拿到此页面的详情
      post({
        url: 'dwPurchase/PurchaseOrderDetail/getList',
        data: {
          purchaseOrderId: record['id'],
        },
      }).then(({data, code}: any) => {
        if (code === 200) {
          //赋值
          pageData.tqDataList = data
          getSlAndDj(
              pageData.tqDataList.map((item) => {
                return item['materialCode']
              })
          )
          gridOptionsz111.value.setRowData(data)
          ckNum()
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      // dataForm.settlementCode = dataForm.settlementCode.toUpperCase();
    }

    const tjWl = () => {
      for (let item in isDataList) {
        isDataList[item] = ''
      }
      pageData1.showAdd = true
    }
    const isDataList = reactive({
      materialName: '',
      specName: '',
      batchName: '',
      unit: '',
      needNum: '',
      applyNum: '',
    })

    // let isDataLists:any = ref([])
    let isDataLists: any = ref([])
    const sideOks = () => {
      let ids: any = []
      // gridOptions11.value.getSelectedRows().map((item: any) => {
      //   return id
      // })
      for (let i = 0; i < gridOptions11.value.getSelectedRows().length; i++) {
        var ob = {}
        ob['id'] = gridOptions11.value.getSelectedRows()[i].did
        ids.push(ob)
      }
      formRef.value?.validate().then((err) => {
        if (!err) {
          let isKong = false
          // table.dataList = table.dataList.filter(function (o) {
          //     return (!selectedRowKeys.value.includes(o["uid"]))
          // });
          // selectedRowKeys.value = [];
          pageData.tqDataList.forEach(function (o: any) {
            if (pageData1.title == '创建采购单') {
              o['id'] = null
            }
            if (o['needNum'] == 0) {
              isKong = true
            }
          })

          if (
              dataForm['applyDepartment'] == '' ||
              dataForm['applyPerson'] == '' ||
              dataForm['applyType'] == '' ||
              dataForm['planDeliveryDate'] == '' ||
              dataForm['providerName'] == '' ||
              dataForm['moneyType'] == ''
          ) {
            Message.warning({
              content: '请将必填字段填写完',
              duration: 5000,
            })
            return
          }
          // if (isKong) {
          //   Message.warning({
          //     content: '填写的数量必须大于0',
          //     duration: 5000,
          //   })
          //   return
          // }

          let list = []
          for (let i = 0; i < pageData.tqDataList.length; i++) {
            var ob = {}
            for (let key in pageData.tqDataList[i]) {
              ob[key] = pageData.tqDataList[i][key]
            }
            ob['useCompany'] = dataForm.useCompany
            ob['purchaseApplyDetailId'] = pageData.tqDataList[i].purchaseApplyDetailId
            list.push(ob)
          }
          if (pageData1.title == '创建采购单') {
            dataForm['submitState'] = 1
            let useDepartment: string[] = []
            let useDepartmentId = ''
            // pageData.tqDataList.map((item: any) => {
            //     item.useDepartment123 = []
            //     item.useDepartment123 = item.useDepartment.split(',').filter((item1: string) => {return item1 && item1.trim()})
            //     item.useDepartment = [...new Set(item.useDepartment123)].join(',')
            //     useDepartmentId += item.useDepartmentId
            //   })
            pageData.tqDataList.map((item: any) => {
              useDepartment.push(
                  ...item.useDepartment.split(',').filter((item1: string) => {
                    return item1 && item1.trim()
                  })
              )
              useDepartmentId += item.useDepartmentId + '/'
            })
            useDepartment = useDepartment.filter((item: string) => {
              return item && item.trim()
            })
            dataForm.useDepartment = [...new Set(useDepartment)].join(',')
            dataForm.useDepartmentId = [...new Set(useDepartmentId)].join('')

            post({
              url: 'dwPurchase/PurchaseOrder/insertList',
              data: {
                ...dataForm,
                purchaseOrderDetail: list,
                applyIds: ids,

                // purchaseApplyId: gridOptions11.value.getSelectedRows().map((o: any) => {
                //   return o.id
                // }),
                // PurchaseApplyDetail:gridOptions11.value.getSelectedRows()
              },
            }).then((res: any) => {
              if (res.code === 200) {
                // gridOptions11.value.getSelectedRows().map((o: any) => {
                //   o.useCompanyName = o.useCompanys
                // })
                post({
                  url: 'dwPurchase/PurchaseOrder/upRedis',
                  data: gridOptions11.value.getSelectedRows().map((o: any) => {
                    return o.id
                  }),
                })

                formRef.value?.resetFields()
                doRefreshs()
                //调查询申购单号的数据
                // cxAllInfo()
                Message.success({
                  content: '保存成功!',
                  duration: 5000,
                })
                pageData1.showAdd = false
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          } else {
            post({
              url: 'dwPurchase/PurchaseOrder/updateList',
              data: {
                ...dataForm,
                purchaseOrderDetail: list,
                // needList: selectedRowKeys.value
              },
            }).then((res: any) => {
              if (res.code === 200) {
                doRefresh()
                selectedRowKeys.value = []
                formRef.value?.resetFields()
                //调查询申购单号的数据
                cxAllInfo()
                Message.success({
                  content: '保存成功!',
                  duration: 5000,
                })
                pageData1.showAdd = false
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          }
        }
      })
    }

    let selectedRowKeys1 = ref()
    const cancelsDel = () => {
      if (pageData1.showAdd) {
        return
      } else {
        pageData.showAdd = false
      }
    }

    const scWl = () => {
      if (selectedRowKeys1.value == 0) {
        Message.error('请选择要删除的数据')
        return
      }
      let filList = pageData.xqDataList.filter(function (o: any) {
        return selectedRowKeys1.value.includes(o['id'])
      })
      pageData.xqDataList = pageData.xqDataList.filter(function (o: any) {
        return !selectedRowKeys1.value.includes(o['id'])
      })
      var mOb = {}

      filList.forEach(function (o: any) {
        if ((mOb[o['materialName']] = undefined)) {
          mOb[o['materialName']] = 0
        } else {
          mOb[o['materialName']] += o['needNum']
        }
      })
      isDataLists.forEach(function (o: any) {
        mOb[o['materialName']]
      })
      for (let i = 0; i < isDataLists.length; i++) {
        for (var key in isDataLists[i]) {
          for (var key1 in mOb) {
            if (key == key1) {
              isDataLists[i]['needNum'] - mOb[key1]
            }
          }
        }
      }
      selectedRowKeys1.value = []
    }
    //下拉框得到焦点
    const focusSelq = () => {
      selCxAllq({needDepartment: ''})
    }
    //下拉数据
    const optionsq = ref<any>(pageData.nameListq)
    const loadingq = ref(false)
    const handleSearchq = (value: any) => {
      if (value) {
        const ob = {needDepartment: value}
        loadingq.value = true
        window.setTimeout(() => {
          selCxAllq(ob)
          optionsq.value = pageData.nameListq
          loadingq.value = false
        }, 200)
      } else {
        optionsq.value = []
      }
    }

    //下拉框查询
    function selCxAllq(val: any) {
      post({
        url: 'dwPurchase/purchaseNeed/getDropValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameListq = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //下拉框得到焦点
    const focusSelqs = () => {
      selCxAllqs({materialName: '', auditState: 1})
    }
    //下拉数据
    const optionsqs = ref<any>(pageData.nameListqs)
    const loadingqs = ref(false)
    const handleSearchqs = (value: any) => {
      if (value) {
        const ob = {materialName: value, auditState: 1}
        loadingqs.value = true
        window.setTimeout(() => {
          selCxAllq(ob)
          optionsqs.value = pageData.nameListqs
          loadingqs.value = false
        }, 200)
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAllqs(val: any) {
      post({
        url: 'dwPurchase/MaterialInfo/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // console.log(data)
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameListqs = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    function doRefreshs() {
      pageData.pageLoading = true
      post({
        url: 'dwPurchase/PurchaseApply/getPurchaseApplyDataLink',
        data: {
          // auditState: 1,
          applyCode: pageData.dropDownData123,
          // purchaseNeedCode: pageData.dropDownData,
          companyEntity: pageData.companyEntity,
          auditState: 1,
          selectType: 1,
          processedState: 0,
          // processedState: 0,
          // finishState: 1,
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              table.handleSuccess(data)
              // pagination1.setTotalSize(data.total)
              gridOptions11.value.setRowData(data)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }

    //查询本人已提交信息
    const cxAllYtj = () => {
      //拿到此页面的详情
      pageData.pageLoading = true
      post({
        url: 'dwPurchase/PurchaseApply/getPurchaseApplyDataLink',
        data: {
          applyCode: pageData.dropDownData,
          auditState: 1,
          selectType: 0,
          processedState: 1,
          // processedState: 1,
          // finishState: 0,
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              // pageData.xqDataList = data.data
              // // pagination.setTotalSize(data.total);
              // gridOptionsz.value.setRowData(data.data)
              table.handleSuccess(data)
              // pagination1.setTotalSize(data.total)
              gridOptionsz.value.setRowData(data)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }
    const selectSh = () => {
      pagination.page = 1
      doRefreshs()
    }

    const tableColumns = useTableColumn([
      {
        title: '申购单号',
        key: 'applyCode',
        dataIndex: 'applyCode',
        width: 150,
      },
      {
        title: '主体',
        key: 'companyEntity',
        dataIndex: 'companyEntity',
        width: 150,
      },
      {
        title: '申购公司',
        key: 'applyCompanys',
        dataIndex: 'applyCompanys',
        width: 150,
      },
      {
        title: '申购部门',
        key: 'applyDepartment',
        dataIndex: 'applyDepartment',
        width: 150,
      },
      // {
      //     title: "物料名称",
      //     key: "materialName",
      //     dataIndex: "materialName",
      //     width: 150
      // },
      // {
      //     title: "申购数量",
      //     key: "applyNum",
      //     dataIndex: "applyNum",
      //     width: 150
      // },
      {
        title: '申购人',
        key: 'applyPerson',
        dataIndex: 'applyPerson',
        width: 150,
      },
      {
        title: '申购类型',
        key: 'applyType',
        dataIndex: 'applyType',
        slotName: 'applyType',
        width: 150,
      },
      {
        title: '计划交货日期',
        key: 'planDeliveryDate',
        dataIndex: 'planDeliveryDate',
        width: 150,
      },
      {
        title: '物料编号',
        key: 'materialCode',
        dataIndex: 'materialCode',
        width: 150,
      },
      {
        title: '物料名称',
        key: 'materialName',
        dataIndex: 'materialName',
        width: 150,
      },
      {
        title: '规格',
        key: 'specName',
        dataIndex: 'specName',
        width: 150,
      },

      {
        title: '单位',
        key: 'unit',
        dataIndex: 'unit',
        width: 150,
      },
      {
        title: '需求数量',
        key: 'needNum',
        dataIndex: 'needNum',
        width: 150,
      },
      {
        title: '申购数量',
        key: 'applyNum',
        dataIndex: 'applyNum',
        width: 150,
      },
      {
        title: '库存数量',
        key: 'stockNum',
        dataIndex: 'stockNum',
        slotName: 'stockNum',
        width: 150,
      },
      // {
      //   title: '欠数',
      //   key: 'oweNum',
      //   dataIndex: 'oweNum',
      //   width: 150,
      // },
      {
        title: '采购公司',
        key: 'useCompanys',
        dataIndex: 'useCompanys',
        width: 150,
      },
      {
        title: '采购部门',
        key: 'useDepartment',
        dataIndex: 'useDepartment',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        slotName: 'remark',
        width: 150,
      },
      // {
      //   title: '操作',
      //   key: 'id',
      //   slotName: 'action',
      //   width: 180,
      //   fixed: 'right',
      // },
    ])

    let visible = ref(false)
    let visible2 = ref(false)
    const tqxqd = () => {
      visible.value = true
    }
    window.onbeforeunload = function () {
      onClose()
      setTimeout(() => {
      }, 30000)
    }
    onUnmounted(() => {
      onClose()
    })
    const timer = ref<any>()
    //关闭定时器
    const onClose = () => {
      let detailUIDs: any = []
      gridOptions11.value.getSelectedRows().forEach((item: any) => {
        detailUIDs.push(item.detailUID)
      })
      clearInterval(timer.value)
      post({
        url: 'dwPurchase/PurchaseOrder/upRedis',
        data: detailUIDs,
      })
      detailUIDs = []
    }
    const handleBeforeOk = () => {
      getFirmGroup()
      if (gridOptions11.value.getSelectedRows().length == 0) {
        visible.value = true
        Message.error('请勾选数据')
        return
      }
      let selectData = gridOptions11.value.getSelectedRows()
      if (!selectData.every((item: any) => item.companyEntity === selectData[0].companyEntity)) {
        Message.error('请勾选相同的主体')
        return
      }
      // getBmGroup(dataForm.useCompany)
      pageData.tqDataList = gridOptions11.value.getSelectedRows()

      //拿到税率和单价
      getSlAndDj(
          pageData.tqDataList.map((item) => {
            return item['materialCode']
          })
      )
      for (let item in dataForm) {
        dataForm[item] = ''
      }
      if (dataForm.moneyType == null || dataForm.moneyType == '') {
        dataForm.moneyType = '人民币'
      }
      // table.handleSuccess([])
      // 加锁
      post({
        url: 'dwPurchase/PurchaseOrder/redisOut',
        data: gridOptions11.value.getSelectedRows().map((o: any) => {
          return o.id
        }),
      }).then(({data, code, message}: any) => {
        if (code === 200) {
          // pageData.tqDataList.map((item) => {
          //   item.purchaseNum = item.oweNum
          // })
          pageData1.showAdd = true
          let detailUIDs: any = []
          gridOptions11.value.getSelectedRows().forEach((item: any) => {
            detailUIDs.push(item.detailUID)
          })
          timer.value = setInterval(() => {
            post({
              url: 'dwPurchase/PurchaseOrder/redisOut',
              data: detailUIDs,
            })
          }, 30000)
          post({
            url: '/dwPurchase/PurchaseOrder/getCodeGenerate',
            data: gridOptions11.value.getSelectedRows().map((item: any) => {
              return {
                id: item.id,
                useCompany: item.useCompany,
                useDepartmentId: item.useDepartmentId,
                useCompanys: item.useCompanys,
                useDepartment: item.useDepartment,
                purchasePerson: item.purchasePerson,
                materialCode: item.materialCode,
                materialName: item.materialName,
                applyNum: item.applyNum,
              }
            }),
          }).then((res: any) => {
            if (res.code == 200) {
              let detailUIDs: any = []
              gridOptions11.value.getSelectedRows().forEach((item: any) => {
                detailUIDs.push(item.detailUID)
              })
              // merge()
              dataForm.purchaseCode = res.data.purchaseCode
              dataForm.createName = res.data.List[0].applyPerson
              dataForm.purchaseDate = res.data.List[0].applyDate
              dataForm.purchasePerson = res.data.List[0].purchasePerson
              dataForm.useCompanys = res.data.List[0].useCompanys
              dataForm.useCompany = res.data.List[0].useCompany
              dataForm.useDepartmentId = res.data.List[0].useDepartmentId
              dataForm.useDepartment = res.data.List[0].useDepartment
              dataForm.companyEntity = selectData[0].companyEntity
              const {List} = res.data
              pageData.tqDataList.forEach((item: any, index: any) => {
                if (item.materialCode == List[index].materialCode) {
                  item.purchaseUnit = List[index].purchaseUnit
                  // item.purchaseNum = numList[index].number
                  item.convertRate = List[index].convertRate
                  // item.price = numList[index].price
                  // item.amount = item.amount
                }
              })

              ckNum()
            }
            pageData1.showAdd = true
            pageData1.title = '创建采购单'
          })

          //打开弹窗
        } else {
          if (data != '') {
            let applyCode = ''
            let StrUname = ''
            data.forEach(function (o: any) {
              if (applyCode == '') {
                applyCode = o['applyCode']
              } else {
                if (applyCode.indexOf(o['applyCode']) == -1) {
                  applyCode += '、' + o['applyCode']
                }
              }

              if (StrUname == '') {
                StrUname = o['name']
              } else {
                if (StrUname.indexOf(o['name']) == -1) {
                  StrUname += '、' + o['name']
                }
              }
            })
            Message.error({
              content: '您勾选的' + applyCode + '申购单正在被' + StrUname + '使用中！！！',
              duration: 10000,
            })
            return
          } else {
            Message.error({
              content: message,
              duration: 10000,
            })
          }
        }
      })
      //拿到物料明细
      let list = []

      for (let i = 0; i < gridOptions11.value.getSelectedRows().length; i++) {
        var ob = {}
        ob['purchaseApplyId'] = gridOptions11.value.getSelectedRows()[i].id
        ob['purchaseApplyDetailId'] =
            gridOptions11.value.getSelectedRows()[i].purchaseApplyDetailId
        list.push(ob)
      }
      // post({
      //   url: 'dwPurchase/PurchaseApplyDetail/getMuchPurchaseApplyDetail',
      //   data: list,
      // }).then(({ data, code }: any) => {
      //   if (code === 200) {
      //   } else {
      //     Message.error({
      //       content: '查询失败！',
      //       duration: 5000,
      //     })
      //   }
      // })

      visible.value = false
    }
    const cancelsDels = () => {
      // table.dataList = []
      table.handleSuccess([])
      selectedRowKeys.value = []
      visible.value = false
    }

    //下拉框得到焦点
    const focusSelx = () => {
      selCxAllx({settlementName: ''})
    }
    //下拉数据
    const optionsx = ref<any>(pageData.nameList)
    const loadingx = ref(false)
    const handleSearchx = (value: any) => {
      if (value) {
        const ob = {settlementName: value}
        loadingx.value = true
        window.setTimeout(() => {
          selCxAllx(ob)
          optionsx.value = pageData.nameList
          loadingx.value = false
        }, 200)
      } else {
        optionsx.value = []
      }
    }

    //下拉框查询
    function selCxAllx(val: any) {
      post({
        url: 'dwPurchase/SettlementType/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //下拉框得到焦点
    const focusSelqq = () => {
      selCxAllqq({deliveryType: ''})
    }
    //下拉数据
    const optionsqq = ref<any>(pageData.nameListqq)
    const loadingqq = ref(false)
    const handleSearchqq = (value: any) => {
      if (value) {
        const ob = {deliveryType: value}
        loadingqq.value = true
        window.setTimeout(() => {
          selCxAllqq(ob)
          optionsqq.value = pageData.nameListqq
          loadingqq.value = false
        }, 200)
      } else {
        optionsqq.value = []
      }
    }

    //下拉框查询
    function selCxAllqq(val: any) {
      post({
        url: 'dwPurchase/LogisticType/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameListqq = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //下拉框得到焦点
    const focusSelz = () => {
      selCxAllz({providerName: ''})
    }
    //下拉数据
    const optionsz = ref<any>(pageData.nameListz)
    const loadingz = ref(false)
    const handleSearchz = (value: any) => {
      if (value) {
        const ob = {providerName: value}
        loadingz.value = true
        window.setTimeout(() => {
          selCxAllz(ob)
          optionsz.value = pageData.nameListz
          loadingz.value = false
        }, 200)
      } else {
        optionsz.value = []
      }
    }

    //下拉框查询
    function selCxAllz(val: any) {
      post({
        url: 'dwPurchase/Provider/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.nameListz = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //下拉框得到焦点
    const focusSels = () => {
      selCxAlls({purchaseType: ''})
    }
    //下拉数据
    const optionss = ref<any>(pageData.nameLists)
    const loadings = ref(false)
    const handleSearchs = (value: any) => {
      if (value) {
        const ob = {purchaseType: value}
        loadings.value = true
        window.setTimeout(() => {
          selCxAlls(ob)
          optionss.value = pageData.nameLists
          loadings.value = false
        }, 200)
      } else {
        optionss.value = []
      }
    }

    //下拉框查询
    function selCxAlls(val: any) {
      post({
        url: 'dwPurchase/PurchaseType/PurchaseTypeValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameLists = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const focusBl = () => {
      post({
        url: 'dict/dictTypeDetail/getListByCodeType?codeType=14',
      }).then((res: any) => {
        if (res.code == 200) {
          pageData.blTypeList = res.data
        }
      })
    }
    //tabs切换
    const changetabs = (key: any) => {
      // table.handleSuccess([])
      pageData.isKey = key
      if (pageData.isKey == 1) {
        selectSh()
      } else if (pageData.isKey == 2) {
        cxAllInfo()
      } else if (pageData.isKey == 3) {
        cxAllYtj()
      } else if (pageData.isKey == 4) {
        selectSh4()
      }
      // selectedRowKeys.value = []
    }

    //查询此人的采购单信息
    const cxAllInfo = () => {
      pageData.pageLoading = true
      //调查询申购单号的数据
      post({
        url: 'dwPurchase/PurchaseOrder/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          purchaseCode: pageData.dropDownData1,
          selectType: 0,
          auditState: 0,
        },
      })
          .then((res: any) => {
            if (res.code === 200) {
              isDataLists.value = res.data.list
              pagination.setTotalSize(res.data.total)
              gridOptions.value.setRowData(res.data.list)
              // gridOptions.value.getSelectedRows().map((item:any) => {
              //   pageData.tqDataList.map((item1) => {
              //   item.useCompanyName = item1.useCompanys
              // })
              // })
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              })
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }
    const visible1 = ref(false)
    //查看详情按钮
    const cxDetails = (record: any) => {
      visible1.value = true
      post({
        url: 'dwPurchase/PurchaseOrderDetail/getList',
        data: {
          purchaseOrderId: record['id'],
        },
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.isDetailsList = data
          pageData.isDetailsList.map((item: any) => {
            item.useCompanys = item.useCompanyName
          })
          ckNum3()
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    const cxDetails1 = (record: any, num: any) => {
      if (num == 1) {
        visible2.value = true
      } else {
        visible1.value = true
      }

      post({
        url: 'dwPurchase/PurchaseApply/getDetail',
        data: {
          page: 1,
          size: pagination.pageSize,
          // "auditState": 0,
          // "submitState": 0,
          applyCode: record['applyCode'],
        },
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.isDetailsList = data[0]['purchaseApplyDetail']
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //拿到所有公司
    // const foucusUseFrim = (num: any) => {
    //   let ob = {}
    //   if (num == 1) {
    //     ob['firmName'] = ''
    //     ob['department'] = ''
    //     // ob['firmTypeId'] = ""
    //   }
    //   if (num == 2) {
    //     ob['firmName'] = ''
    //     ob['department'] = ''
    //     // ob['firmTypeId'] = ""
    //   }

    //   if (num == 3) {
    //     if (dataForm.useCompany !== '' && dataForm.useCompany !== undefined) {
    //       let list = pageData.firmListsy.filter(function (o: any) {
    //         return o['id'] == dataForm.useCompany
    //       })
    //       // let lists = pageData.firmList.filter((o: any) => {
    //       //     return o['id'] == dataForm.settlementCompany
    //       // })
    //       if (list.length > 0) {
    //         dataForm.useCompanyName = list[0]['typeName']
    //           ? list[0]['typeName'] + '-' + list[0]['firmName']
    //           : list[0]['firmName']
    //         // dataForm.useCompanyName = lists[0]['firmName']
    //         ob['firmName'] = list[0]['firmName']
    //         ob['department'] = list[0]['department']
    //         ob['firmTypeId'] = list[0]['firmTypeId']
    //       }
    //     } else {
    //       Message.warning({
    //         content: '请先选择采购公司',
    //         duration: 5000,
    //       })
    //     }
    //   }

    //   getFrimList(ob, num)
    // }
    const options2 = ref(pageData.firmList)
    const loading2 = ref(false)

    const handleSearch2 = (value: any) => {
      if (value) {
        loading2.value = true

        options2.value = pageData.firmList
        loading2.value = false
      } else {
        options2.value = []
      }
    }
    // function getFrimList(ob: any, nums: any) {
    //   post({
    //     url: 'org/firmGroup/getFirmInfoByMap',
    //     data: ob,
    //   }).then((result: any) => {
    //     if (result.code === 200) {
    //       if (nums == 1) {
    //         pageData.firmList = result.data
    //       }
    //       if (nums == 2) {
    //         pageData.firmListsy = result.data
    //       }
    //       if (nums == 3) {
    //         pageData.bmListsy = result.data
    //       }
    //     } else {
    //       Message.error(result.message)
    //     }
    //   })
    // }
    const cancelis = () => {
      pageData1.showAdd = false
      post({
        url: 'dwPurchase/PurchaseOrder/upRedis',
        data: selectedRowKeys.value,
      })
    }
    //公司改变 部门为=空
    // const changeGs = () => {
    //   dataForm.useDepartment = ''
    //   let firmNames: any;
    //   pageData.firmListsy.forEach((item: any) => {
    //     if (item.id == dataForm.useCompany) {
    //       firmNames = item.typeName ? item.typeName + '-' + item.firmName : item.firmName
    //     }
    //   })
    //   dataForm.address = firmNames
    // }
    const gridOptions11 = ref()
    const gridReadys11 = (params: any) => {
      gridOptions11.value = params.api
    }
    const defaultColDefs11 = {
      sortable: true,
      resizable: true,
      filter: true,
    }
    let tcs11: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName == 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `
            <a-space>
              <a-button type="primary" size="mini" @click="a1">详情</a-button>
            </a-space>
          `,
          setup(props: any) {
            const a1 = () => {
              cxDetails1(props.params.data, 1)
            }
            return {
              a1,
            }
          },
        }
      }
      if (o.slotName === 'applyType') {
        obj['filterParams'] = {
          valueFormatter: function (params: any) {
            return params.value == '0'
                ? '加急'
                : params.value == '1'
                    ? '计划'
                    : params.value == '2'
                        ? '临时'
                        : ''
          },
        }
        obj['cellRenderer'] = {
          template: `
            <a-space>
              <div style="color:red;font-weight: bolder;" v-if="isDatas.applyType == '0'">
                加急
              </div>
              <div style="color:green;font-weight: bolder;" v-if="isDatas.applyType == '1'">
                计划
              </div>
              <div style="color:blue;font-weight: bolder;" v-if="isDatas.applyType == '2'">
                临时
              </div>
            </a-space>`,
          setup(props: any) {
            const isDatas = ref(props.params.data)
            return {
              isDatas,
            }
          },
        }
      }
      return obj
    })

    let as11 = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tcs11 = as11.concat(tcs11)

    const gridOptions = ref()
    const gridReadys = (params: any) => {
      gridOptions.value = params.api
    }
    const defaultColDefs = {
      sortable: true,
      resizable: true,
      filter: true,
    }
    let tcs: any[] = tableColumns1.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 150
        obj['lockPosition'] = 'right'
        obj['cellRenderer'] = {
          template: `
            <a-space size="medium">
              <el-button v-if="(isDtas.auditState == 0) && e" style="color:#165dff;" link
                         @click="a1">

                修改
              </el-button>
              <el-button style="color:#165dff;" link @click="a2" v-if="f">
                详情
              </el-button>
            </a-space>
          `,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            const a1 = () => {
              editHandler(props.params.data)
            }
            const a2 = () => {
              cxDetails(props.params.data)
            }
            return {
              e: pageData.isEdit,
              f: pageData.isDetail,
              isDtas,
              a1,
              a2,
            }
          },
        }
      }
      return obj
    })

    let as = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tcs = as.concat(tcs)

    const gridOptionsz = ref()
    const gridReadysz = (params: any) => {
      gridOptionsz.value = params.api
    }
    const defaultColDefsz = {
      sortable: true,
      resizable: true,
      filter: true,
    }
    let tcsz: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['cellRenderer'] = {
          template: `
            <el-button style="color:#165dff;" link
                       @click="a1">
              详情
            </el-button>
          `,
          setup(props: any) {
            const a1 = () => {
              cxDetails1(props.params.data, 1)
            }
            return {
              a1,
            }
          },
        }
      }
      if (o.slotName === 'applyType') {
        obj['filterParams'] = {
          valueFormatter: function (params: any) {
            return params.value == '0'
                ? '加急'
                : params.value == '1'
                    ? '计划'
                    : params.value == '2'
                        ? '临时'
                        : ''
          },
        }
        obj['cellRenderer'] = {
          template: `
            <a-space>
              <div style="color:red;font-weight: bolder;" v-if="isDatas.applyType == '0'">
                加急
              </div>
              <div style="color:green;font-weight: bolder;" v-if="isDatas.applyType == '1'">
                计划
              </div>
              <div style="color:blue;font-weight: bolder;" v-if="isDatas.applyType == '2'">
                临时
              </div>
            </a-space>`,
          setup(props: any) {
            const isDatas = ref(props.params.data)
            return {
              isDatas,
            }
          },
        }
      }
      return obj
    })

    let asz = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tcsz = asz.concat(tcsz)

    const gridOptionsz111 = ref()
    const gridReadysz111 = (params: any) => {
      gridOptionsz111.value = params.api
    }
    const defaultColDefsz111 = {
      sortable: true,
      resizable: true,
      filter: true,

      flex: 1,
    }
    let tcsz111: any[] = tableColumns3.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      o['width'] = '200px'
      if (o.slotName === 'purchaseNum') {
        obj['cellRenderer'] = {
          template: `
            <a-input-number @change="a" v-model="isDtas.purchaseNum" class="input-demo bacClass" :min="0"
                            :max="10000000000000000000"/>`,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            nextTick(() => {
              props.params.data.purchaseNum = props.params.data.applyNum
            })
            const a = () => {
              numchange(props.params.data)
            }
            return {
              a,
              isDtas,
            }
          },
        }
      }
      if (o.slotName === 'convertRate') {
        obj['cellRenderer'] = {
          template: `
            <a-input-number v-model="isDtas.convertRate" class="input-demo bacClass" :min="0"
                            :max="10000000000000000000"/>`,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            return {
              isDtas,
            }
          },
        }
      }
      if (o.slotName === 'price') {
        obj['cellRenderer'] = {
          template: `
            <a-input-number @change="a" v-model="isDtas.price" class="input-demo bacClass" :min="0"/>`,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            if (props.params.data.price == '' || props.params.data.price == null) {
              props.params.data.price = 0
            }
            const a = () => {
              numchange(props.params.data)
            }
            return {
              a,
              isDtas,
            }
          },
        }
      }
      if (o.slotName === 'taxRate') {
        obj['cellRenderer'] = {
          template: `
            <a-input-number @change="a" v-model="isDtas.taxRate" class="input-demo bacClass" :min="0" :max="1"
                            :precision="2" :step="0.01"/>`,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            if (props.params.data.taxRate == '' || props.params.data.taxRate == null) {
              props.params.data.taxRate = 0
            }
            const a = () => {
              // numchange(props.params.data)
            }
            return {
              a,
              isDtas,
            }
          },
        }
      }
      if (o.key === 'amount') {
        obj['cellRenderer'] = {
          template: `
            <div>{{ isDtas.price * isDtas.purchaseNum }}</div>`,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            return {
              isDtas,
            }
          },
        }
      }
      if (o.slotName === 'remark') {
        obj['cellRenderer'] = {
          template: `
            <a-input class="bacClass" v-model="isDtas.remark"/>
          `,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            return {
              isDtas,
            }
          },
        }
      }

      if (o.slotName === 'HistoricalPrice') {
        obj['cellRenderer'] = {
          template: `
            <el-button style="color:#165dff;" link @click="View">单价历史记录</el-button>
          `,
          setup(props: any) {
            const isDtas = ref(props.params.data)
            const View = () => {
              pagination2.page = 1
              ViewHistoricalUnitPrice(props.params.data)
            }
            return {
              View,
              isDtas,
            }
          },
        }
      }

      return obj
    })
    let asz111 = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tcsz111 = asz111.concat(tcsz111)
    const localeText1: any = ref(localeText)
    const huiche = () => {
      selectSh()
    }
    const selectInfo = () => {
      pagination.page = 1
      cxAllInfo()
    }
    const huiche2 = () => {
      selectInfo()
    }
    const huiche3 = () => {
      cxAllYtj()
    }
    const getFirmGroup = () => {
      post({
        url: 'org/baCompany/getTreeCompanyByUser',
        data: {},
      }).then(({code, data}) => {
        if (code === 200) {
          pageData.firmGroupList = data
          pageData.firmGroupList1 = data
        }
      })
    }

    //查看单价历史记录
    function ViewHistoricalUnitPrice(data: any) {
      console.log(data)
      post({
        url: 'dwPurchase/purchasePriceDetail/getPage',
        data: {
          page: pagination2.page,
          size: pagination2.pageSize,
          materialCode: data.materialCode,
        },
      }).then(({code, data}) => {
        if (code === 200) {
          visible5.value = true
          pageData.historicalList = data.list
          pagination2.setTotalSize(data.total)
        }
      })
    }

    let casOb = ref()
    const casOb1 = ref()
    //公司改变
    const cascaderChange = (event: any, val: any) => {
      //拿到选中的这个节点数组
      setTimeout(function () {
        if (casOb.value.selectViewValue.length != 0) {
          pageData.title = casOb.value.selectViewValue[0]['label']
          dataForm.useCompanyName = casOb.value.selectViewValue[0]['label']
        }
      }, 100)
      ckNum()
      // getBmGroup(val)
      dataForm.useDepartmentId = ''
      pageData.bmList = []
    }
    //部门改变
    const cascaderChange1 = (val: any) => {
      //拿到选中的这个节点数组
      setTimeout(function () {
        if (casOb1.value.selectViewValue.length != 0) {
          pageData.title1 = casOb1.value.selectViewValue[0]['label']
          dataForm.useDepartment = casOb1.value.selectViewValue[0]['label']
          dataForm.useDepartmentId = val
        }
      }, 100)
    }
    // 获取部门列表
    const getBmGroup = (val: any) => {
      post({
        url: 'org/baCompany/getDepartmentTree?companyId=' + val,
      }).then((result) => {
        if (result.code === 200) {
          pageData.bmList = result.data
        }
      })
    }
    const casOb2 = ref()
    //公司改变
    const cascaderChange2 = (event: any, val: any) => {
      // dataForm.department = null
      //拿到选中的这个节点数组
      setTimeout(function () {
        if (casOb2.value.selectViewValue.length != 0) {
          pageData.title2 = casOb2.value.selectViewValue[0]['label']
          dataForm.settlementCompanyName = casOb2.value.selectViewValue[0]['label']
          dataForm.settlementCompanyId = val
        }
      }, 100)
      // getBmGroup1(val)
    }

    const proChange = () => {
      let list = pageData.nameListz.filter(function (o: any) {
        return o['id'] == dataForm.providerId
      })
      dataForm.providerName = list[0]['providerName']
    }

    const gridOption4 = ref()
    const gridReady4 = (params: any) => {
      gridOption4.value = params.api
    }
    const defaultColDef4 = {
      sortable: true,
      resizable: true,
      filter: true,
    }
    //采购单列表
    const tableColumns4 = useTableColumn([
      {
        title: '采购单号',
        key: 'purchaseCode',
        dataIndex: 'purchaseCode',
        width: 150,
      },
      {
        title: '编制日期',
        key: 'purchaseDate',
        dataIndex: 'purchaseDate',
        width: 150,
      },
      {
        title: '供应商名称',
        key: 'providerName',
        dataIndex: 'providerName',
        width: 150,
      },
      {
        title: '采购类型',
        key: 'purchaseType',
        dataIndex: 'purchaseType',
        width: 150,
      },
      {
        title: '计划交货日期',
        key: 'planDeliveryDate',
        dataIndex: 'planDeliveryDate',
        width: 150,
      },
      {
        title: '合同号',
        key: 'orderNo',
        dataIndex: 'orderNo',
        width: 150,
      },
      {
        title: '币种',
        key: 'moneyType',
        dataIndex: 'moneyType',
        width: 150,
      },
      {
        title: '采购员',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '付款方式',
        key: 'settlementType',
        dataIndex: 'settlementType',
        width: 150,
      },
      {
        title: '交货方式',
        key: 'logisticType',
        dataIndex: 'logisticType',
        width: 150,
      },
      {
        title: '结算公司',
        key: 'settlementCompanyName',
        dataIndex: 'settlementCompanyName',
        width: 150,
      },
      {
        title: '采购公司',
        key: 'useCompanyName',
        dataIndex: 'useCompanyName',
        width: 150,
      },
      {
        title: '采购部门',
        key: 'useDepartment',
        dataIndex: 'useDepartment',
        width: 150,
      },
      {
        title: '制单人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '状态',
        key: 'auditState',
        dataIndex: 'auditState',
        slotName: 'auditState',
        width: 150,
        fixed: 'right',
      },
      {
        title: '审核人',
        key: 'auditPerson',
        dataIndex: 'auditPerson',
        width: 150,
      },
      {
        title: '审核日期',
        key: 'auditDate',
        dataIndex: 'auditDate',
        width: 150,
      },
      {
        title: '修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '修改日期',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 150,
      },
    ])
    let tc4: any[] = tableColumns4.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'auditState') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 110
        obj['cellRenderer'] = {
          template: `
            <el-tag v-if="isDatas.auditState == 0" type="warning">待审核
            </el-tag>
            <el-tag v-if="isDatas.auditState == 1" type="success">审核通过
            </el-tag>
            <a-space v-if="isDatas.auditState == 2">
              <el-tag type="info">审核驳回</el-tag>

            </a-space>
            <el-tag v-if="isDatas.auditState == 3" type="info">完结
            </el-tag>
          `,
          setup(props: any) {
            const isDatas = ref(props.params.data)
            return {
              isDatas,
            }
          },
        }
      }
      return obj
    })
    const huiche4 = () => {
      selectSh4()
    }
    let a4 = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc4 = a4.concat(tc4)

    //采购单处理  查询方法
    function doRefresh4() {
      pageData.pageLoading = true
      post({
        url: 'dwPurchase/PurchaseOrder/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          purchaseCode: pageData.dropDownData4,
          selectType: 0,
          auditState: 1,
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              pagination.setTotalSize(data.total)
              gridOption4.value.setRowData(data.list)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }

    const selectSh4 = () => {
      pagination.page = 1
      doRefresh4()
    }

    //打印按钮
    let visiblecg4 = ref(false)
    let idDtaDy: any = ref([])
    let idDtaDys: any = ref({
      purchaseCode: '',
      purchasePerson: '',
      purchaseDate: '',
      providerName: '',
      settlementCompany: '',
    })
    let idpro: any = ref({
      contactPerson: '',
      contactPhone: '',
      providerAddress: '',
    })
    let dataTime = ref([])
    let dataTime2 = ref([])

    const dayCogu = () => {
      if (gridOption4.value.getSelectedRows().length == 0) {
        Message.error('请先勾选')
        return
      }
      if (gridOption4.value.getSelectedRows().length > 1) {
        Message.error('只能勾选一条')
        return
      }
      let uid: any = []
      table.dataList.forEach((item: any, index: any) => {
        if (gridOption4.value.getSelectedRows()[0].id == item.id) {
          uid.push(item.uid)
          idDtaDys.value = item
          dataTime.value = item.purchaseDate.split(' ')
          dataTime2.value = item.purchaseDate.split(' ')
          if (item.auditState == 1) {
            uid.forEach((item: any) => {
              post({
                url: 'dwPurchase/PurchaseOrder/getListId',
                data: {
                  id: gridOption4.value.getSelectedRows()[0].id,
                  rejectState: 0,
                },
              }).then((res: any) => {
                if (res.code == 200) {
                  idDtaDy.value = res.data.list
                  idpro.value = res.data.provider
                }
                visiblecg4.value = true
              })
            })
          } else {
            Message.error('未审核或审核为通过')
            return
          }
        }
      })
    }
    const print = () => {
      printJS({
        printable: 'ofpurchase2',
        type: 'html',
        targetStyles: ['*'],
      })
    }
    //库存数量
    const ckNum = () => {
      post({
        url: '/wms/ironwareStockSummary/getStockNumProcurement',
        data: pageData.tqDataList.map((item: any) => {
          return {
            materialCode: item.materialCode,
            companyId: dataForm.useCompany,
            materialName: item.materialName,
          }
        }),
      }).then((res: any) => {
        const {data} = res
        pageData.tqDataList.forEach((item: any, index: any) => {
          data.forEach((item1: any) => {
            if (item.materialCode == item1.materialCode) {
              item.stockNum = item1.stockNum
              if (Number(item.stockNum) >= Number(item.applyNum)) {
                Message.warning(`物料名为 ${item.materialName} 的单据有库存!`)
                pageData1.showAdd = true
              }
            }
          })
        })
      })
    }
    //库存数量
    const ckNum2 = () => {
      post({
        url: '/wms/ironwareStockSummary/getStockNumProcurement',
        data: pageData.isDetailsList.map((item: any) => {
          return {
            materialCode: item.materialCode,
            companyId: item.useCompany,
            materialName: item.materialName,
          }
        }),
      }).then((res: any) => {
        const {data} = res
        pageData.isDetailsList.map((item: any, index: any) => {
          if (item.materialCode == data[index].materialCode) {
            item.stockNum = data[index].stockNum
          }
        })
      })
    }
    //详情中的 库存数量
    const ckNum3 = () => {
      post({
        url: '/wms/ironwareStockSummary/getStockNumProcurement',
        data: pageData.isDetailsList.map((item: any) => {
          return {
            materialCode: item.materialCode,
            companyId: gridOptions.value.getSelectedRows()[0].useCompany,
            materialName: item.materialName,
          }
        }),
      }).then((res: any) => {
        const {data} = res
        pageData.isDetailsList.map((item: any, index: any) => {
          if (item.materialCode == data[index].materialCode) {
            item.stockNum = data[index].stockNum
          }
        })
      })
    }

    const numchange = (val: any) => {
      var numCount = val.price * val.purchaseNum
      pageData.tqDataList.map((o: any) => {
        if (o.id == val.id) {
          o.amount = numCount
        }
      })
    }

    // 送货地址下拉框
    const focusAddress = () => {
      getAddressList('')
    }
    const searchAddress = (value: any) => {
      if (value) {
        loading.value = true
        getAddressList(value)
        options.value = pageData.dzList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const getAddressList = (val: any) => {
      post({
        url: 'dict/dictTypeDetail/getList',
        data: {
          codeType: 35,
          detailName: val,
        },
      }).then(({code, data}: any) => {
        if (code == 200) {
          pageData.dzList = data
        } else {
          Message.error({
            content: '查询失败',
            duration: 5000,
          })
        }
      })
    }

    const pagingList1: any = ref(pagingList)
    const permissionStore = usePermission()
    if (permissionStore.hasPermisson('cgcgd.cgdxg1')) {
      pageData.isEdit = true
    }
    if (permissionStore.hasPermisson('cgcgd.cgdxq1')) {
      pageData.isDetail = true
    }

    const visible5 = ref(false)
    const handleOk5 = () => {
      visible5.value = false
    }
    const handleCancel5 = () => {
      visible5.value = false
    }

    //拿到税率和单价
    function getSlAndDj(list: any) {
      post({
        url: 'dwPurchase/MaterialInfo/getMaterialInfoPara',
        data: list,
      }).then(({code, data}: any) => {
        if (code == 200) {
          pageData.tqDataList.forEach(function (o: any) {
            o['taxRate'] = data[o['materialCode']]['taxRate']
            o['price'] = data[o['materialCode']]['price']
            o['bigClassName'] = data[o['materialCode']]['bigClassName']
          })
          pageData.tqDataList.sort((a, b) => {
            return a.bigClassName > b.bigClassName ? 1 : -1
          })
        } else {
          Message.error({
            content: '查询失败',
            duration: 5000,
          })
        }
      })
    }

    //打印预览PDF
    const printPdf = () => {
      if (gridOption4.value.getSelectedRows().length == 0) {
        Message.error('请先勾选')
        return
      }
      if (gridOption4.value.getSelectedRows().length > 1) {
        Message.error('只能勾选一条')
        return
      }
      post({
        url: '/dwPurchase/PurchaseOrder/getListDY',
        data: {id: gridOption4.value.getSelectedRows()[0].id},
        responseType: 'blob',
      }).then((res) => {
        let reader = new FileReader()
        reader.readAsDataURL(res)
        reader.onload = function () {
          let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '')
          printJS({printable: pdfBase64, type: 'pdf', base64: true})
        }
      })
    }
    // 主体下拉框
    const focusSelZt = () => {
      handleSearchZt('')
    }
    const handleSearchZt = (value: any) => {
      if (typeof value == 'object') {
        value = ''
      }
      post({
        url: 'org/baCompany/getFieldValue',
        data: {company_entity: value},
      }).then(({code, data, message}: any) => {
        if (code == 200) {
          pageData.companyEntityList = data
        } else {
          Message.error({
            content: message,
            duration: 5000,
          })
        }
      })
    }
    return {
      handleSearchZt,
      focusSelZt,
      printPdf,
      pagination2,
      PageSize1,
      change2,
      tableColumns5,
      handleOk5,
      visible5,
      handleCancel5,
      ViewHistoricalUnitPrice,
      focusAddress,
      searchAddress,
      getAddressList,
      permissionStore,
      selectInfo,
      numchange,
      ckNum3,
      ckNum2,
      ckNum,
      huiche4,
      dataTime,
      dataTime2,
      idpro,
      idDtaDys,
      idDtaDy,
      print,
      visiblecg4,
      dayCogu,
      selectSh4,
      tc4,
      defaultColDef4,
      doRefresh4,
      tableColumns4,
      gridReady4,
      gridOption4,
      proChange,
      // merge,
      // oweChange,
      casOb,
      casOb1,
      casOb2,
      pagingList1,
      cascaderChange2,
      cascaderChange,
      cascaderChange1,
      getFirmGroup,
      // selectSh4,
      // dayCogu,
      onClose,
      tbsData,
      huiche,
      huiche2,
      huiche3,
      localeText1,
      tcsz111,
      defaultColDefsz111,
      gridReadysz111,
      gridOptionsz111,
      tcsz,
      defaultColDefsz,
      gridReadysz,
      gridOptionsz,
      tcs,
      defaultColDefs,
      gridReadys,
      gridOptions,
      tcs11,
      defaultColDefs11,
      gridReadys11,
      gridOptions11,
      PageSize,
      change1,
      visible2,
      // changeGs,
      cxDetails1,
      cancelis,
      // foucusUseFrim,
      handleSearch2,
      options2,
      loading2,
      zjArrays1,
      casaders,
      zjArrays,
      xqOptions,
      focusSelqq,
      handleSearchqq,
      loadingx,
      handleSearchx,
      focusSelx,
      cancelsDels,
      visible1,
      handleBeforeOk,
      tqxqd,
      visible,
      tableColumns,
      selectSh,
      handleSearchqs,
      focusSelqs,
      loadingqs,
      loadingq,
      focusSelq,
      handleSearchq,
      scWl,
      cancelsDel,
      focusSelz,
      handleSearchz,
      selectedRowKeys1,
      isDataLists,
      sideOks,
      handleSearchs,
      focusSels,
      isDataList,
      tjWl,
      tableColumns1,
      tableColumns3,
      cxDetails,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns2,
      table,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      inputBlur,
      isChiese,
      options,
      loading,
      handleSearch,
      focusSel,
      handleSearch1,
      focusSel1,
      options1,
      pageData1,
      pagination1,
      headerShow,
      focusBl,
      changetabs,
      cxAllInfo,
      cxAllYtj,
      onSelect(dateString: any, date: any) {
        pageData.dropDownDataqszs = {
          startDate: dateString[0],
          endDate: dateString[1],
        }
      },
      onClear() {
        pageData.dropDownDataqszs = {}
      },
      addXqiu() {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (isDataLists.value.length == 0) {
              Message.error('请提取申购单')
              return
            } else {
              dataForm.id = null
              pageData.xqDataList.forEach(function (o: any) {
                o['id'] = undefined
              })
              post({
                url: 'dwPurchase/PurchaseOrder/insertList',
                data: {
                  ...dataForm,
                  // purchaseOrderDetail: isDataLists.value
                  purchaseApplyDetail: pageData.xqDataList,
                },
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  isDataLists.value = []
                  table.dataList = []
                  for (let item in dataForm) {
                    dataForm[item] = ''
                  }
                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            }
          }
        })
      },
      delQk() {
        formRef.value?.resetFields()
        isDataLists.value = []
        for (let item in dataForm) {
          dataForm[item] = ''
        }
      },
    }
  },
  components: {PageTabelLayout, Toolbar, },
}
</script>
<style scoped lang="less">
.addStley {
  width: 90%;
  margin: 0 auto;

  .isAdd {
    width: 100%;
    height: 120px;
    text-align: right;
  }
}

.xqdxx {
  display: flex;
}

.isTable {
  margin-top: 100px;
  width: 90%;
  margin: 0 auto;
  border: 1.2px solid #ccc;
  text-align: center;
  border-collapse: collapse;

  td {
    border: 1.2px solid #ccc;
  }

  th {
    border: 1.2px solid #ccc;
  }
}

#dys {
  display: flex;
  width: 90%;
  margin: 0 auto;
  justify-content: space-between;
  font-weight: 1000;

  div {
    width: 200px;
  }
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
